package com.gjxx.buss.service;

import com.alibaba.fastjson2.JSON;
import com.gjxx.common.utils.HexStringUtils;
import com.gjxx.common.utils.StringUtils;
import com.gjxx.netty.codec.BitOperator;
import com.gjxx.netty.session.Session;
import com.gjxx.netty.session.SessionManager;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;

/**
 * @author maogf
 * @date 2018/06/04
 */
@Slf4j
public class BaseMsgProcessService {

	protected SessionManager sessionManager;

	public BaseMsgProcessService() {
		this.sessionManager = SessionManager.getInstance();
	}

	protected ByteBuf getByteBuf(byte[] arr) {
		ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.directBuffer(arr.length);
		byteBuf.writeBytes(arr);
		return byteBuf;
	}

	public boolean sendClient(Channel channel, byte[] arr) throws InterruptedException {
		ByteBuf byteBuf = Unpooled.copiedBuffer(arr);
		log.info("发送消息:{}", JSON.toJSONString(buf2Str(byteBuf)));
		ChannelFuture future = channel.writeAndFlush(byteBuf).sync();
		if (!future.isSuccess()) {
			log.error("发送数据出错:{}", future.cause());
			return false;
		}else{
			return true;
		}
	}

	public void send2Client(Channel channel, byte[] arr,String mark) throws InterruptedException {
		try {
			ByteBuf byteBuf = Unpooled.copiedBuffer(arr);
			String str = HexStringUtils.toHexString(arr);
			channel.writeAndFlush(byteBuf).addListener(new ChannelFutureListener() {
				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					StringBuilder sb = new StringBuilder();
					if(!StringUtils.isEmpty(mark)){
						sb.append("【").append(mark).append("】");
					}
					if (future.isSuccess()) {
						log.info(sb.toString()+"回复客户端成功:"+str);
					} else {
						log.info(sb.toString()+"回复客户端失败:"+str);
					}
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
			log.error("回复客户端异常:" + e.getMessage());
		}
	}

	private String buf2Str(ByteBuf in) {
		byte[] dst = new byte[in.readableBytes()];
		in.getBytes(0, dst);
		return HexStringUtils.toHexString(dst);
	}

	protected int getFlowId(Channel channel, int defaultValue) {
		Session session = this.sessionManager.findBySessionId(Session.buildId(channel));
		if (session == null) {
			return defaultValue;
		}

		return session.currentFlowId();
	}

	protected int getFlowId(Channel channel) {
		return this.getFlowId(channel, 0);
	}

	public static void main(String[] args) throws UnsupportedEncodingException {
		byte[] GBKDecode = "123".getBytes("GBK");// 文本信息

		BitOperator bitOperator = new BitOperator();
		byte[] b_msgType = bitOperator.integerTo2Bytes(2);
		ByteBuf byteBuf = Unpooled.copiedBuffer(b_msgType);
		byte[] dst = new byte[byteBuf.readableBytes()];
		byteBuf.getBytes(0, dst);
		String str =  HexStringUtils.toHexString(dst);
		System.out.println(str);
	}

}
